package 树;

public class Demo07 {
    /*
    * 方法一: 使用局部变量 回溯
    * */
    static class Solution {
        private int count;
        public boolean hasPathSum(TreeNode root, int targetSum) {
            if(root == null){
                return false;
            }

            count+=root.val;
            int cur = count;

            if(root.left == null && root.right == null){
                if(count == targetSum){
                    return true;
                }
                return false;
            }

            boolean flag = hasPathSum(root.left,targetSum);
            if(flag){
                return flag;
            }

            count = cur; // 回溯
            return hasPathSum(root.right,targetSum);
        }
    }

    /*
    * 方法二: 不借助局部变量, 官方题解
    * */
    static class Solution2{
        public boolean hasPathSum(TreeNode root, int sum) {
            if (root == null) {
                return false;
            }
            if (root.left == null && root.right == null) {
                return sum == root.val;
            }
            return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        }
    }
}
